package com.vue3.blog.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vue3.blog.common.resp.PageVO;
import com.vue3.blog.common.util.PageUtil2;
import com.vue3.blog.common.util.RequestUtil2;
import com.vue3.blog.common.util.StrUtil2;
import com.vue3.blog.domain.dto.CommentDTO;
import com.vue3.blog.domain.entity.CommentEntity;
import com.vue3.blog.domain.vo.CommentListVO;
import com.vue3.blog.domain.vo.CommentTreeVO;
import com.vue3.blog.mapper.CommentMapper;
import com.vue3.blog.service.ICommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Mr.小朱同学
 * @version 1.0.0
 * @date 2025/6/13 19:43
 * @description 文章评论
 */
@Service
public class CommentService extends ServiceImpl<CommentMapper, CommentEntity> implements ICommentService {
    /**
     * 保存评论
     */
    @Override
    public void saveComment(CommentDTO comment) {
        CommentEntity entity = new CommentEntity();
        BeanUtils.copyProperties(comment, entity);
        entity.setCommentator(comment.getNickname());
        entity.setContact(comment.getEmail());
        entity.setCreatedTime(new Date());
        // 获取请求IP地址
        entity.setRequestIp(RequestUtil2.getClientIp());
        entity.setProvince("");
        this.save(entity);
    }

    /**
     * 删除评论
     *
     * @param id 评论ID
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeComment(Long id) {
        // 先将所有子级评论删除
        LambdaQueryWrapper<CommentEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CommentEntity::getParentId, id);
        this.remove(wrapper);
        // 在删除当前评论
        this.removeById(id);
    }

    /**
     * 评论列表
     */
    @Override
    public List<CommentTreeVO> getFrontendCommentList(Long postId) {
        LambdaQueryWrapper<CommentEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CommentEntity::getPostId, postId);
        List<CommentEntity> entityList = this.list(wrapper);
        if (CollUtil.isEmpty(entityList)) {
            return Collections.emptyList();
        }
        List<CommentTreeVO> voList = new ArrayList<>();
        List<CommentEntity> parentList = entityList.stream().filter(ent -> Objects.equals(ent.getParentId(), 0L)).collect(Collectors.toList());
        if (CollUtil.isEmpty(parentList)) {
            return Collections.emptyList();
        }
        parentList.forEach(ent -> {
            CommentTreeVO vo = new CommentTreeVO();
            BeanUtils.copyProperties(ent, vo);
            vo.setIsReply(0);
            vo.setChildren(dfs(entityList, vo));
            voList.add(vo);
        });
        // 按照时间降序排序
        voList.sort((o1, o2) -> o2.getCreatedTime().compareTo(o1.getCreatedTime()));
        return voList;
    }

    /**
     * 评论列表
     */
    @Override
    public PageVO<CommentListVO> getCommentList() {
        PageUtil2.startPage();
        LambdaQueryWrapper<CommentEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.orderByDesc(CommentEntity::getCreatedTime);
        List<CommentEntity> entityList = this.list(wrapper);
        if (CollUtil.isEmpty(entityList)) {
            return PageUtil2.endPage(Collections.emptyList());
        }
        List<CommentListVO> voList = new ArrayList<>();
        entityList.forEach(ent -> {
            CommentListVO vo = new CommentListVO();
            BeanUtils.copyProperties(ent, vo);
            vo.setIsReply(StrUtil2.isNotEmpty(ent.getReplyCommentator()) ? 1 : 0);
            voList.add(vo);
        });
        return PageUtil2.endPage(entityList, voList);
    }

    /**
     * 评论数
     */
    @Override
    public Long getCommentCount() {
        return this.count();
    }

    private List<CommentTreeVO> dfs(List<CommentEntity> entityList, CommentTreeVO parentVo) {
        // 构造评论树结构
        List<CommentEntity> parentList = entityList.stream().filter(ent -> Objects.equals(ent.getParentId(), parentVo.getId())).collect(Collectors.toList());
        if (CollUtil.isEmpty(parentList)) {
            return Collections.emptyList();
        }
        List<CommentTreeVO> children = new ArrayList<>();
        parentList.forEach(parent -> {
            CommentTreeVO vo = new CommentTreeVO();
            BeanUtils.copyProperties(parent, vo);
            vo.setIsReply(1);
            vo.setReplyCommentator(parentVo.getCommentator());
            vo.setChildren(this.dfs(entityList, vo));
            children.add(vo);
        });
        // 按照时间降序排序
        children.sort((o1, o2) -> o2.getCreatedTime().compareTo(o1.getCreatedTime()));
        return children;
    }
}